package com.cardone.common.security;

import com.google.common.collect.Maps;
import lombok.Synchronized;

import javax.crypto.Cipher;
import java.security.Key;
import java.security.Security;
import java.util.Map;

/**
 * Created by c100000002 on 15-1-28.
 */
public class DESCipher {
    private static Map<String, DESCipher> desCipherMap = Maps.newHashMap();

    private static final String DEFAULTKEY = "C1";

    private static final String DES = "DES";

    /**
     * 将参数字节数组转换为16进制值表示组合而成的字符串。
     *
     * @param arrB 需要转换的byte数组
     * @return String 转换后的字符串
     * @throws Exception JAVA异常
     */
    public static String byteGrpToHexStr(final byte[] arrB) throws Exception {
        final int iLen = arrB.length;
        final StringBuffer tempSB = new StringBuffer(iLen * 2);
        for (int i = 0; i < iLen; i++) {
            int intTmp = arrB[i];
            while (intTmp < 0) {
                intTmp = intTmp + 256;
            }
            if (intTmp < 16) {
                tempSB.append("0");
            }
            tempSB.append(Integer.toString(intTmp, 16));
        }
        return tempSB.toString();
    }

    /**
     * 将参数16进制值表示组合而成的字符串转换为字节数组。
     *
     * @param strIn 需要转换的字符串
     * @return byte[] 转换后的byte数组
     * @throws Exception JAVA异常
     */
    public static byte[] hexStrToByteGrp(final String strIn) throws Exception {
        final byte[] arrB = strIn.getBytes();
        final int iLen = arrB.length;
        final byte[] arrOut = new byte[iLen / 2];
        for (int i = 0; i < iLen; i = i + 2) {
            final String strTmp = new String(arrB, i, 2);
            arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
        }
        return arrOut;
    }

    public static void main(final String[] args) throws Exception {
        final DESCipher des = DESCipher.newDESCipher("");
        final String str = des.encrypt("中华人民共和国");
        System.out.println(str);
        final String dstr = des.decrypt(str);
        System.out.println(dstr);
    }

    @Synchronized
    public static DESCipher newDESCipher(final String key) throws Exception {
        if (DESCipher.desCipherMap.containsKey(key)) {
            return DESCipher.desCipherMap.get(key);
        }

        final DESCipher desCipher = new DESCipher(key);

        DESCipher.desCipherMap.put(key, desCipher);

        return desCipher;
    }

    private Cipher encryptCipher = null;

    private Cipher decryptCipher = null;

    /**
     * 默认构造方法，使用默认密钥
     *
     * @throws Exception
     */
    public DESCipher() throws Exception {
        this(DESCipher.DEFAULTKEY);
    }

    /**
     * 指定密钥构造方法
     *
     * @param strKey 指定的密钥
     * @throws Exception JAVA异常
     */
    public DESCipher(final String strKey) throws Exception {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        final Key key = this.getKey(strKey.getBytes());
        this.encryptCipher = Cipher.getInstance(DESCipher.DES);
        this.encryptCipher.init(Cipher.ENCRYPT_MODE, key);
        this.decryptCipher = Cipher.getInstance(DESCipher.DES);
        this.decryptCipher.init(Cipher.DECRYPT_MODE, key);
    }

    /**
     * 解密字节数组
     *
     * @param arrB 需解密的字节数组
     * @return byte[] 解密后的字节数组
     * @throws Exception JAVA异常
     */
    public byte[] decrypt(final byte[] arrB) throws Exception {
        return this.decryptCipher.doFinal(arrB);
    }

    /**
     * 解密字符串 将参数字符串转换为字节数组后重用decrypt(String)方法进行解密，并将得到的解密字符数组转换为字符串后返回。
     *
     * @param strIn 需解密的字符串
     * @return String 解密后的字符串
     * @throws Exception JAVA异常
     */
    public String decrypt(final String strIn) throws Exception {
        return new String(this.decrypt(DESCipher.hexStrToByteGrp(strIn)));
    }

    /**
     * 加密字节数组
     *
     * @param arrB 需加密的字节数组
     * @return byte[] 加密后的字节数组
     * @throws Exception JAVA异常
     */
    public byte[] encrypt(final byte[] arrB) throws Exception {
        return this.encryptCipher.doFinal(arrB);
    }

    /**
     * 加密字符串 将字符串转换为字节数组后重用encrypt(byte[])方法进行加密，并将得到字节数组转换为字符串返回
     *
     * @param strIn 需加密的字符串
     * @return String 加密后的字符串
     * @throws Exception JAVA异常
     */
    public String encrypt(final String strIn) throws Exception {
        return DESCipher.byteGrpToHexStr(this.encrypt(strIn.getBytes()));
    }

    /**
     * 从指定字符串生成密钥，密钥所需的字节数组长度为8位 不足8位时后面补0，超出8位只取前8位
     *
     * @param arrBTmp 构成该字符串的字节数组
     * @return Key 生成的密钥
     * @throws Exception JAVA异常
     */
    private Key getKey(final byte[] arrBTmp) throws Exception {
        final byte[] arrB = new byte[8];
        for (int i = 0; (i < arrBTmp.length) && (i < arrB.length); i++) {
            arrB[i] = arrBTmp[i];
        }
        final Key key = new javax.crypto.spec.SecretKeySpec(arrB, DESCipher.DES);
        return key;
    }
}

